let path = require('path')
let Koa = require('koa')
let chalk = require('chalk')
let webpack = require('webpack')
let proxy = require('koa-proxies')
let serve = require("koa-static")
// import compress from 'koa-compress'

// 中间件容器，把webpack处理后的文件传递给一个服务器
let wdm = require('./middleware/devMiddleware')
// 在内存中编译的插件，不写入磁盘来提高性能
let whm = require('./middleware/hotMiddleware')

let webpackConfig = require('../webpack')
let { SERVER_PATH, BUILD_PATH } = require('../config/paths.conf')
let config = require('../config')


const devConfig = webpackConfig(false)
const compiler = webpack(devConfig)
const app = new Koa()

// app.use(compress())

app.use(wdm(compiler, {
    publicPath: devConfig.output.publicPath,
    quiet: true,
    stats: { colors: true },
    watchOptions: devConfig.watchOptions
}))

app.use(whm(compiler))

app.use(serve(path.join(SERVER_PATH, 'static'), {}))
app.use(serve(path.join(BUILD_PATH), {}))

app.use(proxy("/api/**", {
    target: `http://localhost:${config.mockPort}/api`,
    changeOrigin: true,
    logs: true
}))

app.use(proxy("/**", {
    target: `http://localhost:${config.serverPort}`,
    changeOrigin: true,
    logs: true
}))

app.listen(config.clientPort, (err) => {
    if (err) {
        console.error(chalk.yellow(`==> 😭  OMG!!! ${err}`))
    }
    console.info(chalk.green(`==> 🌎  Listening at http://localhost:${config.clientPort}`))

})
